<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 表单
// +----------------------------------------------------------------------
namespace app\controller;
use app\common\File;
use think\facade\View;
use think\facade\Db;

class Form extends Common
{
	//表单列表
	public function index(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = input('param.field').' '.input('param.order');
			}else{
				$order = 'sort desc,id desc';
			}
			$where = [];
			$where[] = ['aid','=',aid];
			if(bid==0){
				if(input('param.bid')){
					$where[] = ['bid','=',input('param.bid')];
				}elseif(input('param.showtype')==2){
					$where[] = ['bid','<>',0];
				}else{
					$where[] = ['bid','=',0];
				}
                if($this->user['bids']){
                    $bids = explode(',',$this->user['bids']);
                    if(!in_array('0',$bids)){
                        $where[] = ['bid','in',$bids];
                    }
                }
			}else{
				$where[] = ['bid','=',bid];
			}
			if(input('param.name')) $where[] = ['name','like','%'.input('param.name').'%'];
			$count = 0 + Db::name('form')->where($where)->count();
			$data = Db::name('form')->where($where)->page($page,$limit)->order($order)->select()->toArray();
			foreach($data as $k=>$v){
				if(strtotime($v['starttime']) > time()){
					$data[$k]['status'] = '<button class="layui-btn layui-btn-sm" style="background-color:#888">未开始</button>';
				}elseif(strtotime($v['endtime']) < time()){
					$data[$k]['status'] = '<button class="layui-btn layui-btn-sm layui-btn-disabled">已结束</button>';
				}else{
					$data[$k]['status'] = '<button class="layui-btn layui-btn-sm" style="background-color:#3e5">进行中</button>';
				}
				if($v['payset'] == 1){
					$st0count = Db::name('form_order')->where('formid',$v['id'])->where('status',0)->where('paystatus',1)->count();
				}else{
					$st0count = Db::name('form_order')->where('formid',$v['id'])->where('status',0)->count();
				}
				$data[$k]['st0count'] = $st0count;
				if($v['bid'] > 0){
					$data[$k]['bname'] = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->value('name');
				}else{
					$data[$k]['bname'] = '平台';
				}
			}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		
		$bids = explode(',',$this->user['bids']);
		if(!in_array('0',$bids)){
			$blist = Db::name('business')->where('aid',aid)->where('id','in',$bids)->order('sort desc,id desc')->column('id,name');
		}else{
			$blist = Db::name('business')->where('aid',aid)->order('sort desc,id desc')->column('id,name');
		}
		View::assign('blist',$blist);
		return View::fetch();
	}
	//编辑
	public function edit(){
		if(input('param.id')){
			if(bid == 0){
				$info = Db::name('form')->where('aid',aid)->where('id',input('param.id/d'))->find();
			}else{
				$info = Db::name('form')->where('aid',aid)->where('bid',bid)->where('id',input('param.id/d'))->find();
			}
            }else{
			$info = array('id'=>'','content'=>'[]','commissionset'=>'-1');
		}
        $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
        $default_cid = $default_cid ? $default_cid : 0;
        $aglevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('can_agent','<>',0)->order('sort,id')->select()->toArray();
		$levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
		View::assign('aglevellist',$aglevellist);
		View::assign('levellist',$levellist);
		View::assign('info',$info);
		return View::fetch();
	}
	//保存
	public function save(){
		$info = input('post.info/a');
		$info['commissiondata1'] = jsonEncode(input('post.commissiondata1/a'));
		$info['commissiondata2'] = jsonEncode(input('post.commissiondata2/a'));
		$datatype = input('post.datatype/a');
		$dataval1 = input('post.dataval1/a');
		$dataval2 = input('post.dataval2/a');
		$dataval3 = input('post.dataval3/a');
		$dataval4 = input('post.dataval4/a');
		$dataval5 = input('post.dataval5/a');
        $dataval6 = [];
        $dataval7 = [];
		//附件下载压缩包名称
        $dataval_query = input('post.dataval_query/a');
		$dhdata = array();
		foreach($datatype as $k=>$v){
			if($dataval3[$k]!=1) $dataval3[$k] = 0;
			$dhdata[] = [
			'key'=>$v,
			'val1'=>$dataval1[$k],
			'val2'=>$dataval2[$k],
			'val3'=>$dataval3[$k],
			'val4'=>$dataval4[$k],
			'val5'=>($dataval5 ? $dataval5[$k] : ''),
			'val6'=>$dataval6[$k]??0,
			'val7'=>$dataval7[$k]??0,
			'query'=>($dataval_query[$k] ? $dataval_query[$k] : '0'),
			];
		}
		$info['content'] = json_encode($dhdata,JSON_UNESCAPED_UNICODE);
		if(bid!=0){
			$info['commissionset'] = -1;
		}
		if($info['id']){
			if(bid == 0){
				Db::name('form')->where('aid',aid)->where('id',$info['id'])->update($info);
			}else{
				Db::name('form')->where('aid',aid)->where('bid',bid)->where('id',$info['id'])->update($info);
			}
			\app\common\System::plog('编辑自定义表单'.$info['id']);
		}else{
			$info['aid'] = aid;
			$info['bid'] = bid;
			$info['createtime'] = time();
			$id = Db::name('form')->insertGetId($info);
			\app\common\System::plog('添加自定义表单'.$id);
		}
		return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);
	}
	//删除
	public function del(){
		$ids = input('post.ids/a');
		if(bid == 0){
			Db::name('form')->where('aid',aid)->where('id','in',$ids)->delete();
		}else{
			Db::name('form')->where('aid',aid)->where('bid',bid)->where('id','in',$ids)->delete();
		}
		\app\common\System::plog('删除自定义表单'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	
	//复制
	public function copyform(){
		$id = input('post.id/d');
		$form = Db::name('form')->where('aid',aid)->where('bid',bid)->where('id',$id)->find();
		if(!$form){
			return json(['status'=>0,'msg'=>'表单不存在']);
		}
		$form['id'] = '';
        $form['name'] = $form['name'].'-复制';
		$newid = Db::name('form')->insertGetId($form);
		return json(['status'=>1,'msg'=>'操作成功','newid'=>$newid]);
	}
	

	//表单数据
	public function record(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = input('param.field').' '.input('param.order');
			}else{
				$order = 'id desc';
			}
			$where = [];
			$where[] = ['aid','=',aid];
			if(bid != 0){
				$where[] = ['bid','=',bid];
			}
			if(input('param.formid')) $where[] = ['formid','=',input('param.formid/d')];
			if(input('param.name')) $where[] = ['name','like','%'.input('param.name').'%'];
			if(input('param.ctime') ){
				$ctime = explode(' ~ ',input('param.ctime'));
				$where[] = ['createtime','>=',strtotime($ctime[0])];
				$where[] = ['createtime','<',strtotime($ctime[1]) + 86400];
			}
			if(input('?param.status') && input('param.status')!==''){
				$where[] = ['status','=',input('param.status')];
			}
			if(input('param.tel')){
				$where[] = ['form0|form1|form2|form3|form4|form5|form6|form7|form8|form9|form10','=',input('param.tel')];
			}
			if(input('param.keyword')){
				$where[] = ['form0|form1|form2|form3|form4|form5|form6|form7|form8|form9|form10','like','%'.input('param.keyword').'%'];
			}
			
			$form = Db::name('form')->where('aid',aid)->where('id',input('param.formid/d'))->find();
			$formcontent = json_decode($form['content'],true);

			$count = 0 + Db::name('form_order')->where($where)->count();
			$data = Db::name('form_order')->where($where)->page($page,$limit)->order($order)->select()->toArray();
			foreach($data as $k=>$v){
				$data[$k]['headimg'] = '';
				$data[$k]['nickname'] = '';
				if($v['mid']){
					$member = Db::name('member')->where('id',$v['mid'])->find();
					if($member){
						$data[$k]['headimg'] = $member['headimg'];
						$data[$k]['nickname'] = $member['nickname'];
					}
				}
				$pics = [];
				foreach($formcontent as $k2=>$field){
					if($field['key']=='upload'){
						$pics[] = $v['form'.$k2];
					}
				}
				$data[$k]['pics'] = implode(',',$pics);
			}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		$form = Db::name('form')->where('aid',aid)->where('id',input('param.formid/d'))->find();
		$formcontent = json_decode($form['content'],true);
		View::assign('form',$form);
		View::assign('formcontent',$formcontent);
		return View::fetch();
	}
	//表单数据导出
	public function recordexcel(){
		$form = Db::name('form')->where('aid',aid)->where('id',input('param.formid/d'))->find();
		$formcontent = json_decode($form['content'],true);
		if(input('param.field') && input('param.order')){
			$order = input('param.field').' '.input('param.order');
		}else{
			$order = 'id desc';
		}
		$where = [];
		$where[] = ['aid','=',aid];
		if(bid != 0){
			$where[] = ['bid','=',bid];
		}
		$where[] = ['formid','=',input('param.formid/d')];
		if(input('param.name')) $where[] = ['name','like','%'.input('param.name').'%'];

		if(input('param.ctime') ){
			$ctime = explode(' ~ ',input('param.ctime'));
			$where[] = ['createtime','>=',strtotime($ctime[0])];
			$where[] = ['createtime','<',strtotime($ctime[1]) + 86400];
		}
		if(input('?param.status') && input('param.status')!==''){
			$where[] = ['status','=',input('param.status')];
		}
		if(input('param.keyword')){
			$where[] = ['form0|form1|form2|form3|form4|form5|form6|form7|form8|form9|form10','like','%'.input('param.keyword').'%'];
		}

		$list = Db::name('form_order')->where($where)->order($order)->select()->toArray();
		
		$title = array();
		$title[] = '序号';
		$type = [];
        $type[] = 1;
		foreach($formcontent as $k=>$v){
			$title[]=$v['val1'];
            $type[]=$v['val4'];
		}
		if($form['payset']==1){
			$title[] = '支付状态';
			$title[] = '支付金额';
			$title[] = '支付单号';
			$title[] = '支付时间';
		}
		$title[] = '提交时间';
		$title[] = '状态';
		$title[] = '驳回原因';
		$data = array();
		foreach($list as $v){
			$tdata = array();
			$tdata[] = $v['id'];
			foreach($formcontent as $k=>$d){
				$tdata[] = $v['form'.$k];
			}
			if($form['payset']==1){
				$tdata[] = $v['paystatus'] == 1?'已支付':'未支付';
				$tdata[] = $v['money'];
				$tdata[] = $v['paynum'];
				$tdata[] =  $v['paytime']? date("Y-m-d H:i:s",$v['paytime']) : '';
			}
			$tdata[] = date('Y-m-d H:i:s',$v['createtime']);
			$status = '';
			if($v['status']==0){
				$status = '待处理';
			}elseif($v['status']==1){
				$status = '已确认';
			}elseif($v['status']==2){
				$status = '已驳回';
			}
			if($v['isudel']==1){
				$status.=',用户已删除';
			}
			$tdata[] = $status;
			$tdata[] = $v['reason'];
			$data[] = $tdata;
		}
		$this->export_excel($title,$data,$type);
	}
	//改状态
	public function recordsetst(){
		$ids = input('post.ids/a');
		$st = input('post.st/d');
		$istuikuan = input('post.istuikuan/d');
		if(bid != 0){
			$orderlist = Db::name('form_order')->where('aid',aid)->where('bid',bid)->where('id','in',$ids)->select()->toArray();
		}else{
			$orderlist = Db::name('form_order')->where('aid',aid)->where('id','in',$ids)->select()->toArray();
		}
		foreach($orderlist as $order){
			if($st == 2 && $istuikuan == 1){
				$order['totalprice'] = $order['money'];
				$rs = \app\common\Order::refund($order,$order['money'],input('post.reason'));
				if($rs['status']==0){
					return json(['status'=>0,'msg'=>$rs['msg']]);
				}
				Db::name('form_order')->where('aid',aid)->where('id',$order['id'])->update(['isrefund'=>1]);
			}
			if($st == 2){
				$reason = input('post.reason');
				Db::name('form_order')->where('aid',aid)->where('id',$order['id'])->update(['status'=>$st,'reason'=>$reason]);
			}else{
				Db::name('form_order')->where('aid',aid)->where('id',$order['id'])->update(['status'=>$st]);
			}
			//审核结果通知
			$tmplcontent = [];
			$tmplcontent['first'] = ($st == 1 ? '恭喜您的提交审核通过' : '抱歉您的提交未审核通过');
			$tmplcontent['remark'] = ($st == 1 ? '' : ($reason.'，')) .'请点击查看详情~';
			$tmplcontent['keyword1'] = $order['title'];
			$tmplcontent['keyword2'] = ($st == 1 ? '已通过' : '未通过');
			$tmplcontent['keyword3'] = date('Y年m月d日 H:i');
			\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_shenhe',$tmplcontent,m_url('pages/form/formlog'));
			//订阅消息
			$tmplcontent = [];
			$tmplcontent['thing8'] = $order['title'];
			$tmplcontent['phrase2'] = ($st == 1 ? '已通过' : '未通过');
			$tmplcontent['thing4'] = $reason;
			
			$tmplcontentnew = [];
			$tmplcontentnew['thing2'] = $order['title'];
			$tmplcontentnew['phrase1'] = ($st == 1 ? '已通过' : '未通过');
			$tmplcontentnew['thing5'] = $reason;
			\app\common\Wechat::sendwxtmpl(aid,$order['mid'],'tmpl_shenhe',$tmplcontentnew,'pages/form/formlog',$tmplcontent);
		}
		\app\common\System::plog('修改表单数据状态'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//编辑表单数据
	public function recordedit(){
		$form = Db::name('form')->where('aid',aid)->where('id',input('param.formid/d'))->find();
		if(!$form) return json(['status'=>0,'msg'=>'表单不存在']);
		if(bid !=0 && $form['bid']!=bid) return json(['status'=>0,'msg'=>'表单不存在']);
		$formcontent = json_decode($form['content'],true);
		$id = input('param.id/d');
		if($id){
			$order = Db::name('form_order')->where('aid',aid)->where('formid',$form['id'])->where('id',$id)->find();
			if(!$order) return json(['status'=>0,'msg'=>'数据不存在']);
		}else{
			$order = ['formid'=>$form['id']];
		}
		View::assign('form',$form);
		View::assign('formcontent',$formcontent);
		View::assign('info',$order);
		return View::fetch();
	}
	public function recordsave(){
		$info = input('post.info/a');
		$form = Db::name('form')->where('aid',aid)->where('id',input('param.formid/d'))->find();
		if(!$form) return json(['status'=>0,'msg'=>'表单不存在']);
		if(bid !=0 && $form['bid']!=bid) return json(['status'=>0,'msg'=>'表单不存在']);
		
		$formcontent = json_decode($form['content'],true);

		$data =[];
		$data['mid'] = $info['mid'];
		$data['status'] = $info['status'];
		foreach($formcontent as $k=>$v){
			$value = $info['form'.$k];
			if(is_array($value)){
				$value = implode(',',$value);
			}
			$data['form'.$k] = strval($value);
			if($v['val3']==1 && $data['form'.$k]===''){
				return json(['status'=>0,'msg'=>$v['val1'].' 必填']);
			}
		}

		if($form['payset']==1){
			$price = input('post.price/f');
			$data['money'] = $price;
			$data['paystatus'] = $info['paystatus'];
		}

		if($info['id']){
			$oldinfo = Db::name('form_order')->where('formid',$form['id'])->where('id',$info['id'])->find();
			if(!$oldinfo) return json(['status'=>0,'msg'=>'数据不存在']);
			Db::name('form_order')->where('formid',$form['id'])->where('id',$info['id'])->update($data);
			if($data['status']!= 0 && $data['status'] != $oldinfo['status']){
				$st = $data['status'];
				//审核结果通知
				$tmplcontent = [];
				$tmplcontent['first'] = ($st == 1 ? '恭喜您的提交审核通过' : '抱歉您的提交未审核通过');
				$tmplcontent['remark'] = ($st == 1 ? '' : ($reason.'，')) .'请点击查看详情~';
				$tmplcontent['keyword1'] = $order['title'];
				$tmplcontent['keyword2'] = ($st == 1 ? '已通过' : '未通过');
				$tmplcontent['keyword3'] = date('Y年m月d日 H:i');
				\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_shenhe',$tmplcontent,m_url('pages/form/formlog'));
			}
		}else{
			$data['aid'] = aid;
			$data['bid'] = $form['bid'];
			$data['formid'] = $form['id'];
			$data['title'] = $form['name'];
			$data['createtime'] = time();
			$data['ordernum'] = date('ymdHis').aid.rand(1000,9999);
			$orderid = Db::name('form_order')->insertGetId($data);
			if($form['payset']==1 && $data['money'] > 0 && $data['paystatus']!=1){
				$payorderid = \app\model\Payorder::createorder(aid,$data['bid'],$data['mid'],'form',$orderid,$data['ordernum'],$data['title'],$data['money']);
			}
		}
		return json(['status'=>1,'msg'=>'操作成功']);
	}

	//复制
	public function copyinfo(){
		$id = input('post.id/d');
		$order = Db::name('form_order')->where('aid',aid)->where('bid',bid)->where('id',$id)->find();
		if(!$order){
			return json(['status'=>0,'msg'=>'数据不存在']);
		}
		$order['id'] = '';
		$newid = Db::name('form_order')->insertGetId($order);
		return json(['status'=>1,'msg'=>'操作成功','newid'=>$newid]);
	}
	
	//删除
	public function recorddel(){
		$ids = input('post.ids/a');
		if(bid != 0){
			Db::name('form_order')->where('aid',aid)->where('bid',bid)->where('id','in',$ids)->delete();
		}else{
			Db::name('form_order')->where('aid',aid)->where('id','in',$ids)->delete();
		}
		\app\common\System::plog('删除表单数据'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	public function chooseform(){
		if(request()->isPost()){
			$data = Db::name('form')->where('aid',aid)->where('id',input('post.id/d'))->find();
			return json(['status'=>1,'msg'=>'查询成功','data'=>$data]);
		}
        if(bid==0){
            //商户
            $blist = Db::name('business')->where('aid',aid)->order('sort desc,id desc')->select()->toArray();
            View::assign('blist',$blist);
        }
		return View::fetch();
	}

    //批量打包下载
    public function downloadPics(){
	    return json(['status' => 0, 'msg' => '未获得该功能权限']);
    }
}